//
//  ComposeViewController.swift
//  JMWB
//
//  Created by 个人电脑 on 16/3/24.
//  Copyright © 2016年 个人电脑. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController {
    //底部工具栏距离底部的约束
    @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
    //文本框
    @IBOutlet var customTextView: ComposeTextView!

    private lazy var titleView : ComposeTitleView = ComposeTitleView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
      //设置导航栏
        setupNavigationBar()
      //监听键盘弹出
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //成为第一响应者,已进入即响应
        customTextView.becomeFirstResponder()
    }
    //移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }


}
extension ComposeViewController{

    private func setupNavigationBar(){
       navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "cancelItemClick")
       navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "sendItemClick")
        navigationItem.rightBarButtonItem?.enabled = false
        
        titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 36)
       navigationItem.titleView = titleView
    }
    
   }

extension ComposeViewController{

   @objc private func cancelItemClick(){
     dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func sendItemClick(){
    print("sendItemClick")
    }
    
    @objc private func keyboardWillChangeFrame(note : NSNotification){
//        print(note.userInfo)
        // 1.取出键盘最终frame
        let endFrameValue = note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
        let endFrame = endFrameValue.CGRectValue()
        //2.取出键盘弹出的时间
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        //3.计算工具栏距离底部的约束
        let bottomCons = UIScreen.mainScreen().bounds.height - endFrame.origin.y
        //4.改变工具栏距离底部约束
        toolBarBottomCons.constant = bottomCons
        //5.执行动画
        UIView .animateWithDuration(duration) { () -> Void in
            //更新所有约束
            self.view.layoutIfNeeded()
        }
    }
}
//实现textView的代理方法
extension ComposeViewController : UITextViewDelegate{
//当文字已经发生改变时,会执行该方法 hasText是否有文字
    func textViewDidChange(textView: UITextView) {
        customTextView.placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    //当用户开始拖拽scrollView时会执行该方法
    func scrollViewWillBeginDecelerating(scrollView: UIScrollView) {
        //结束第一响应
        customTextView.resignFirstResponder()
    }
}